import { SvgIcon } from '@/components/icon';
import { message } from 'antd';
import React, { useEffect, useState } from 'react';
import Tables from '@/components/tables/tables';
import PagesHeader from '@/components/pages-header';
import NotData from '@/components/NotData';
import { CaretUpOutlined, CaretDownOutlined } from '@ant-design/icons';
import knowService from '@/api/services/knowService';
import { useParams } from '@/router/hooks';
import { Search } from '@/components/eai-design';
import UnanSwerableDisposeModal from './unanSwerableDisposeModal';
import useModal from '@/hooks/use-modal/useModal';
import { useKnowledgeStore } from '@/store/knowledge';
import TipDesc from '@/components/tipDesc/tipDesc';

const AiUnanswerable: React.FC = () => {
  const modal = useModal('dispose');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [search, setSearch] = useState('');
  const [total, setTotal] = useState(0);
  const { appId = '' } = useParams() as { appId: string };
  const [paginationProps, setPaginationProps] = useState({
    page: 1,
    pageSize: 10,
    searchText: '',
    offset: 0,
    appId: appId,
  });
  const { setUnknownItem, unknownItem } = useKnowledgeStore();
  // 排序状态
  const [sortField, setSortField] = useState<string | undefined>();
  const [sortOrder, setSortOrder] = useState<'ascend' | 'descend' | undefined>();

  const [unknownList, setUnknownList] = useState([]);

  useEffect(() => {
    getList();
  }, [paginationProps, unknownItem]);

  const getList = async () => {
    try {
      const res = await knowService.getUnknownList(paginationProps);
      setUnknownList(res.items || []);
      setTotal(res.total || 0);
    } catch (error) {
      message.error(error as string);
    }
  };

  // 排序处理（只对 unknownList 排序）
  const sortedData = React.useMemo(() => {
    if (!sortField || !sortOrder) return unknownList;
    const sorted = [...unknownList].sort((a, b) => {
      const aValue = a[sortField];
      const bValue = b[sortField];
      if (typeof aValue === 'number' && typeof bValue === 'number') {
        return sortOrder === 'ascend' ? aValue - bValue : bValue - aValue;
      }
      return 0;
    });
    return sorted;
  }, [unknownList, sortField, sortOrder]);

  // 排序点击逻辑
  const handleSortClick = (field: string) => {
    if (sortField !== field) {
      setSortField(field);
      setSortOrder('descend');
    } else if (sortOrder === 'descend') {
      setSortOrder('ascend');
    } else if (sortOrder === 'ascend') {
      setSortField(undefined);
      setSortOrder(undefined);
    } else {
      setSortOrder('descend');
    }
  };

  // 自定义排序表头
  const renderSortTitle = (label: string, field: string) => (
    <span
      className="inline-flex cursor-pointer select-none items-center"
      onClick={() => handleSortClick(field)}
    >
      {label}
      <span className="ml-1 flex flex-col text-xs leading-none">
        <CaretUpOutlined
          style={{
            color: sortField === field && sortOrder === 'ascend' ? '#1677ff' : '#bfbfbf',
            fontSize: 10,
            marginBottom: -2,
          }}
        />
        <CaretDownOutlined
          style={{
            color: sortField === field && sortOrder === 'descend' ? '#1677ff' : '#bfbfbf',
            fontSize: 10,
            marginTop: -2,
          }}
        />
      </span>
    </span>
  );

  // 列定义
  const columns = [
    {
      title: <span>AI无法回答问题</span>,
      dataIndex: 'keyQuestionText',
      key: 'keyQuestionText',
      render: (text: string) => (
        <div className="w-[600px] truncate" title={text}>
          {text}
        </div>
      ),
      width: 300,
    },
    {
      title: renderSortTitle('相关问题数', 'clusterSize'),
      dataIndex: 'clusterSize',
      key: 'clusterSize',
      width: 200,
      render: (_: any, record: any) => record.clusterItems?.length ?? 0,
    },
    {
      title: renderSortTitle('被提及数', 'mentionedTimes'),
      dataIndex: 'mentionedTimes',
      key: 'mentionedTimes',
      width: 200,
    },
    {
      title: <span>操作</span>,
      key: 'action',
      width: 200,
      render: (_: any, record: any) => (
        <div className="flex  gap-4">
          <a
            className="flex cursor-pointer items-center text-@brand-color"
            onClick={() => {
              modal.dispose.open();
              setUnknownItem(record);
            }}
          >
            <SvgIcon icon="edit" size="16" className="mr-1" />
            处理
          </a>
          <a
            className="flex cursor-pointer items-center text-@error-color"
            onClick={() => {
              handleOverlook([record.keyQuestionQaId]);
            }}
          >
            <SvgIcon icon="message-ic21" size="16" className="mr-1" />
            忽略
          </a>
        </div>
      ),
    },
  ];

  // 分页切换
  const handlePageChange = (page: number, pageSize?: number) => {
    setPaginationProps((prev) => ({
      ...prev,
      page,
      pageSize: pageSize || prev.pageSize,
      offset: (page - 1) * (pageSize || prev.pageSize),
    }));
  };

  // 搜索
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value);
    setPaginationProps((prev) => ({
      ...prev,
      searchText: e.target.value,
      page: 1,
      offset: 0,
    }));
  };
  //忽略
  const handleOverlook = async (items?: string[]) => {
    try {
      const targetItems = items || selectedRowKeys;
      await knowService.unknoOverlook({
        keyQuestionQaId: targetItems as string[],
        appId: appId,
      });
      message.success('忽略成功');
      setSelectedRowKeys([]);
      getList();
    } catch (error) {
      message.error(error as string);
    }
  };

  return (
    <div className="flex h-full flex-col bg-white">
      <PagesHeader>
        AI未知问
        <TipDesc title="发现和治理AI无法回答的问题，识别潜在知识盲区" className="!my-0" />
      </PagesHeader>
      <div className="flex flex-1 flex-col rounded-default px-5">
        <div className="my-4 flex items-center justify-between gap-4">
          <div>
            <Search value={search} onChange={handleSearch} placeholder="搜索" />
          </div>
          <div className="  flex items-center">
            <div
              className={`ml-4 flex h-[32px] w-[68px]  items-center justify-center rounded-md border ${
                selectedRowKeys.length > 0
                  ? 'cursor-pointer !border-@brand-color !text-@brand-color'
                  : 'cursor-not-allowed !border-@brand-color-disabled !text-@brand-color-disabled'
              }`}
              onClick={() => {
                if (selectedRowKeys.length > 0) {
                  handleOverlook();
                }
              }}
            >
              <SvgIcon icon="message-ic21" size="20" className="mr-1" />
              忽略
            </div>
          </div>
        </div>
        {/* 表格内容 */}
        <div className="flex flex-1 flex-col">
          {sortedData.length > 0 ? (
            <Tables
              rowSelection={{
                type: 'checkbox',
                selectedRowKeys,
                onChange: setSelectedRowKeys,
              }}
              rowKey="keyQuestionQaId"
              columns={columns}
              dataSource={sortedData}
              pagination={false}
              className="border border-gray-100"
              paginationProps={{
                total: total,
                current: paginationProps.page,
                pageSize: paginationProps.pageSize,
                onChange: handlePageChange,
              }}
            />
          ) : (
            <NotData />
          )}
        </div>
      </div>

      <UnanSwerableDisposeModal
        open={modal.dispose.isOpen}
        onCancel={() => {
          modal.dispose.close();
          getList();
        }}
        onOk={() => {
          modal.dispose.close();
          getList();
        }}
        onOverlook={() => {
          handleOverlook([unknownItem.keyQuestionQaId]);
          modal.dispose.close();
        }}
      />
    </div>
  );
};

export default AiUnanswerable;
